package org.example.judge_comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.judge_comment.mapper.CommentLikeMapper;
import org.example.judge_comment.service.CommentLikeService;
import org.example.judge_comment.service.CommentService;
import org.example.judge_common.util.IdWorker;
import org.example.judge_pojo.Comment;
import org.example.judge_pojo.CommentLike;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;

@Service("CommentLikeServiceImpl")
@Transactional
public class CommentLikeServiceImpl extends ServiceImpl<CommentLikeMapper, CommentLike> implements CommentLikeService {

    @Autowired
    private IdWorker idWorker;

    @Qualifier("CommentServiceImpl")
    @Autowired
    private CommentService commentService;
    @Override
    public Integer countByCommentId(Serializable commentId) {

        return super.count(new QueryWrapper<CommentLike>().eq("comment_id",commentId));
    }

    @Override
    public CommentLike isLike(String commentId, String userId) {
        return super.getOne(new QueryWrapper<CommentLike>().eq("comment_id",commentId).eq("user_id",userId));
    }

    @Override
    public boolean save(CommentLike entity) {
        entity.setId(idWorker.nextId().toString());
        entity.setCreateTime(new Date());
        return super.save(entity);
    }

    @Override
    public boolean remove(String commentId, String userId) {
        return super.remove(new QueryWrapper<CommentLike>().eq("comment_id",commentId).eq("user_id",userId));
    }

    @Override
    public CommentLike clickLike(String commentId, String userId) {
        CommentLike like = this.isLike(commentId, userId);
//        Comment byId = commentService.getById(commentId);
//        if(byId==null)return null;

        if (like!=null){  //取消点赞
            boolean b = commentService.clickLikeSum(commentId, -1);//like_Sum +1
            if(!b)return null;  //表示未修改到数据，不存在comment
            this.remove(commentId,userId);

        }else{  //点赞

            boolean b = commentService.clickLikeSum(commentId, 1); //like_Sum +1
            if(!b)return null; //表示未修改到数据，不存在comment
            like = new CommentLike();
            like.setCommentId(commentId);
            like.setUserId(userId);
            this.save(like);

        }

        return like;
    }
}
